//
//  JMTotalLoanVC.m
//  NewiOSProject
//
//  Created by apple on 2023/9/17.
//  Copyright © 2023 范智渊. All rights reserved.
//

#import "JMTotalLoanVC.h"
#import "JMLoanApplySuccess.h"
#import "JMOrderInfoCell.h"
#import "JMProductHeaderView.h"
#import "JMProductModel.h"

@interface JMTotalLoanVC ()<UITableViewDelegate,UITableViewDataSource>
{
    UIView *contV;
    BOOL hasShowWindow;//是否提示过挽留弹窗
}
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)UIView *bottomView;
@property (nonatomic, strong)JMProductHeaderView *headView;
@property (nonatomic, strong)JMProductModel *model;

@property (nonatomic, strong)YYLabel *agreementLab;//协议 （He leído y estoy de acuerdo con 《Acuerdo de prestamo》）
@property (nonatomic, strong)UIButton *selBtn;//选择框
@property (nonatomic, strong)NSTimer *timer;//当前滑动的值
@property (nonatomic, assign) NSTimeInterval time;
@property (nonatomic, strong)UIButton *btn;//协议按钮《 Politica de privacidad 》
@property (nonatomic, strong)JMLoadingButton *applyBtn;//现在申请按钮（Solicitar ahora）

@end

@implementation JMTotalLoanVC
-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    };
}
// 开启定时器
- (void)startTimer {
    // 如果只有一张，直接放回，不需要开启定时器
//    if (_images.count <= 1) return;
    self.time = 60;
    // 如果定时器已经开启，则先停止再开启
    if (self.timer) [self stopTimer];
    self.timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(setBtn) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    [self.timer fireDate];
}
// 关闭定时器
- (void)stopTimer {
    [self.timer invalidate];
    self.timer = nil;
}
-(void)setBtn{
    self.time -=1;
    if (self.time>0) {
        if (self.time<10) {
            [self.applyBtn setTitle:[NSString stringWithFormat:@"00:0%ld   Solicitar ahora",@(self.time).intValue] forState:(UIControlStateNormal)];
        }else{
            [self.applyBtn setTitle:[NSString stringWithFormat:@"00:%ld   Solicitar ahora",@(self.time).intValue] forState:(UIControlStateNormal)];
        }
    }else{
        [self stopTimer];
        [self.applyBtn setTitle:@"Solicitar ahora" forState:(UIControlStateNormal)];
    }
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.TitleLabel.text = @"Detalles de préstamo";
    self.view.backgroundColor =WhiteColor();
    [self startTime];
    [self getData];
}
-(void)backBtnClick{
    if(hasShowWindow){
        [self.navigationController popToRootViewControllerAnimated:YES];
    }else{
        [JMPublicAlertView showAlertWithFrame:(CGRectMake(0, 0, kAppW()-40, 166)) Title:@"" subTitle:@"Piense de nuevo, el límite de crédito seguirá aumentando！" BottomBtns:@[@"Confirmar"] Position:(JMPublicAlertViewPositionCenter) btnDirection:(JMPublicAlertViewButtonDirectionHor) btnActionBlock:^(NSInteger btnTag) {
            if (hasShowWindow) {
                [super backBtnClick];
            }else{
                hasShowWindow = YES;
            }
        }];
    }
}
-(void)getData{
    
    
    NSMutableArray *arr = @[].mutableCopy;
    for (JMProductModel *mod in self.productModel.ProductPackageList) {
        NSDictionary *dict = @{
            @"amount":mod.amount.stringValue,
            @"id":mod.id.stringValue,
            @"term":mod.term.stringValue,
        };
        [arr addObject:dict];
    }
    
    // [self startAnimating:nil];
    [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(@"/api/loan/total-loan-calculate-flexible") params:@{@"reqList":arr} success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        [self stopAnimating];
        self.model = [JMProductModel mj_objectWithKeyValues:dataDic];
        NSMutableArray *arr = @[].mutableCopy;

        for (NSDictionary *dict in self.model.pairs) {
            [arr addObject:dict];
        }
        self.model.pairs = arr;

        [self setUI];
        
    } fail:^(NSString * _Nonnull errorMsg) {
        [self stopAnimating];
    }];

}
-(void)setUI{
    self.NavImg.backgroundColor = Hex_Str_COLOR(@"#3C57F8");
    self.TitleLabel.textColor = WhiteColor();
    [self.backBtn setImage:ImageNamed(@"ICON／zuo") forState:(UIControlStateNormal)];
    
    
    [self.view addSubview:self.tableView];
    [self.tableView reloadData];
    [self.view addSubview:self.bottomView];
}
//MARK: -UITableViewDataSource UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.model.pairs.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    JMOrderInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JMOrderInfoCell" forIndexPath:indexPath];
    cell.selectionStyle = 0;
    if (indexPath.row < self.model.pairs.count) {
        NSDictionary*dict = self.model.pairs[indexPath.row];
        cell.model = dict;
    }
    return cell;
}

//MARK: -lazyLoad
-(JMProductHeaderView *)headView{
    if (!_headView) {
        _headView = [[JMProductHeaderView alloc]initWithFrame:(CGRectMake(0, 0, kAppW(), 1))];
        _headView.infoModel = self.model;
    }
    return _headView;
}
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,NAVIGATION_BAR_HEIGHT(), kAppW(), kAppH()) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.bounces = NO;
        _tableView.rowHeight = 52;
        [_tableView registerClass:[JMOrderInfoCell class] forCellReuseIdentifier:@"JMOrderInfoCell"]; // 注册UITableViewCell
        _tableView.separatorColor = mainSepartorColor();
        _tableView.sectionHeaderTopPadding = 0;
        _tableView.backgroundColor = Hex_Str_COLOR(@"#fffff");
        [_tableView setTableHeaderView:self.headView];
        _tableView.sectionHeaderTopPadding = 0;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = false;
        }
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    return _tableView;
}
-(UIView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[UIView alloc]initWithFrame:(CGRectMake(0, 0, kAppW(), 1))];
        _bottomView.backgroundColor = WhiteColor();
        _bottomView.layer.shadowColor = HexAlpha_Str_COLOR(@"#000000", 0.1).CGColor;
        _bottomView.layer.shadowRadius = 16;
        _bottomView.layer.shadowOpacity = 1;
        
        [_bottomView addSubview:self.applyBtn];
        [_bottomView addSubview:self.selBtn];
        [_bottomView addSubview:self.agreementLab];
        [_bottomView addSubview:self.btn];
        _bottomView.height = _btn.bottom+JF_BOTTOM_SPACE()+30;
        _bottomView.top = kAppH() - _bottomView.height;
    }
    return _bottomView;
}

-(YYLabel *)agreementLab{
    if(!_agreementLab){
        //协议
        _agreementLab = [[YYLabel alloc]initWithFrame:(CGRectMake(_selBtn.right+12, self.applyBtn.bottom+20,kAppW()-38, FontH(13)))];
        _agreementLab.numberOfLines = 0;
        _agreementLab.centerY = _selBtn.centerY;

        NSString *agreementStr =@"He leido y estoy de acuerdo con 《Acuerdo de prestamo》";
        NSDictionary *attributes = @{NSFontAttributeName:Font(10), NSForegroundColorAttributeName: Hex_Str_COLOR(@"#999999")};
        NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:agreementStr attributes:attributes];
        
        NSRange range0 = [agreementStr rangeOfString:@"He leido y estoy de acuerdo con"];
        @weakify(self)
        [text yy_setTextHighlightRange:range0 color:Hex_Str_COLOR(@"#9B9B9B") backgroundColor:UIColor.clearColor tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
            @strongify(self)
            [self selBtnClick];
        }];
        
        NSRange range = [agreementStr rangeOfString:@"《Acuerdo de prestamo》"];
        [text yy_setTextHighlightRange:range color:Agreement_Text_COLOR() backgroundColor:UIColor.clearColor tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
//            /contract/loan.html
            [JMCommonMethod presentWebviewWithUrl:serviceUrlWith(loginLoanAgreement) andTitle:@"Acuerdo de prestamo"];
        }];
        _agreementLab.attributedText = text;
        
    }
    
    return _agreementLab;
}
-(UIButton *)selBtn{
    if(!_selBtn){
        _selBtn = [JMControl createButtonWithFrame:(CGRectMake(24, self.applyBtn.bottom+20, 24, 24)) ImageName:@"product_unselected" selectedImage:@"product_selected" Target:self Action:@selector(selBtnClick) Title:nil tag:1];
    }
    return _selBtn;
}
-(void)selBtnClick{
    _selBtn.selected = !_selBtn.isSelected;
    self.applyBtn.enable = _selBtn.selected;
}
-(void)applyBtnBtnClick{

    
    NSMutableArray *arr = @[].mutableCopy;
    for (JMProductModel *mod in self.productModel.ProductPackageList) {
        NSDictionary *dict = @{
            @"applyAmount":mod.amount?mod.amount.stringValue:@"0",
            @"isReloan":mod.isReloan.intValue?@"1":@"0",
            @"productId":mod.id.stringValue,
            @"term":mod.term.stringValue,
            @"termUnit":mod.termUnit.stringValue
        };
        [arr addObject:dict];
    }
    NSDictionary *param=@{@"gwApplyReqList":arr};
    [JMCommonMethod uploadStatistics:@"LoanDetails" actionType:@"Apply_Loan_Click" parameters:nil];//@{@"productAndRanks":productAndRanks}

    [JMBaseRequest.sharedInstance requestBasePost:BasePostRequestUrl(@"/api/loan/apply2") params:param successResult:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        NSDictionary *data = dataDic[@"data"];
        NSString *code = dataDic[@"code"];
        NSString *message = dataDic[@"message"];
        [JMCommonMethod uploadStatistics:@"LoanDetails" actionType:@"Apply_Loan_Success" parameters:nil];//@{@"productAndRanks":productAndRanks}

        BOOL showStartV = [dataDic[@"data"] boolValue];
        JMLoanApplySuccess *vc = JMLoanApplySuccess.new;
        vc.showStart = showStartV;
        [self.navigationController pushViewController:vc animated:YES];

    } fail:^(NSString * _Nonnull errorMsg) {
    }];
    
  
}
-(JMLoadingButton *)applyBtn{
    if(!_applyBtn){
        _applyBtn = [[JMLoadingButton alloc]initWithFrame:(CGRectMake(24, 10, kAppW()-48, 56)) title:@"01:00   Solicitar ahora" font:mediumFont(17) titleLabelColor:Button_ENABLE_TEXTCOLOR() backgoundColor:Button_ENABLE_BG_COLOR() action:@selector(applyBtnBtnClick) target:self];
        _applyBtn.cornerRadius = 28;
        _applyBtn.enable = NO;
    }
    return _applyBtn;
}
-(void)delegateBtnClick{
    [JMCommonMethod presentWebviewWithUrl:serviceUrlWith(loginPrivacyAgreement) andTitle:@"Politica de privacidad"];

}
-(UIButton *)btn{
    if(!_btn){
        _btn = [JMControl createButtonWithFrame:(CGRectMake(0, _agreementLab.bottom+30, kAppW(), FontH(15))) Target:self Action:@selector(politicaBtnClick) Title:@"《Politica fr privacidad》" titlColor:Hex_Str_COLOR(@"#222222") font:Font(15) tag:1 backgroundColor:nil];
    }
    return _btn;
}
-(void)dealloc{
    [self stopTimer];
}
@end
